package com.demo.accessibilitykeeper;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.Toast;

/**
 * 自动黑屏遮罩服务
 * 功能：开机自启动黑屏遮罩，每次重启后第一时间开启黑屏
 */
public class AutoMaskService extends Service {
    private static final String TAG = "AutoMaskService";
    private static final String PREFS_NAME = "auto_mask_prefs";
    private static final String KEY_AUTO_MASK_ENABLED = "auto_mask_enabled";
    private static final String KEY_MASK_DELAY = "mask_delay";
    
    private WindowManager windowManager;
    private android.view.View maskView;
    private boolean isMaskVisible = false;
    private Handler handler;
    private Runnable maskRunnable;
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "AutoMaskService created");
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        handler = new Handler(Looper.getMainLooper());
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent != null ? intent.getStringExtra("action") : null;
        
        if ("enable_auto_mask".equals(action)) {
            enableAutoMask();
        } else if ("disable_auto_mask".equals(action)) {
            disableAutoMask();
        } else if ("toggle_auto_mask".equals(action)) {
            toggleAutoMask();
        } else if ("start_mask_immediately".equals(action)) {
            startMaskImmediately();
        }
        
        return START_STICKY;
    }
    
    /**
     * 启用自动黑屏遮罩
     */
    public void enableAutoMask() {
        try {
            Log.d(TAG, "🔧 ENABLING_AUTO_MASK");
            
            // 保存设置
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
            prefs.edit().putBoolean(KEY_AUTO_MASK_ENABLED, true).apply();
            
            // 立即启动遮罩
            startMaskImmediately();
            
            Log.d(TAG, "✅ AUTO_MASK_ENABLED_SUCCESSFULLY");
            Toast.makeText(this, "自动黑屏遮罩已启用", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_ENABLING_AUTO_MASK", e);
        }
    }
    
    /**
     * 禁用自动黑屏遮罩
     */
    public void disableAutoMask() {
        try {
            Log.d(TAG, "🔧 DISABLING_AUTO_MASK");
            
            // 保存设置
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
            prefs.edit().putBoolean(KEY_AUTO_MASK_ENABLED, false).apply();
            
            // 隐藏遮罩
            hideMask();
            
            Log.d(TAG, "✅ AUTO_MASK_DISABLED_SUCCESSFULLY");
            Toast.makeText(this, "自动黑屏遮罩已禁用", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_DISABLING_AUTO_MASK", e);
        }
    }
    
    /**
     * 切换自动黑屏遮罩状态
     */
    public void toggleAutoMask() {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        boolean isEnabled = prefs.getBoolean(KEY_AUTO_MASK_ENABLED, false);
        
        if (isEnabled) {
            disableAutoMask();
        } else {
            enableAutoMask();
        }
    }
    
    /**
     * 立即启动遮罩
     */
    public void startMaskImmediately() {
        try {
            Log.d(TAG, "🎭 STARTING_MASK_IMMEDIATELY");
            
            // 检查是否已经显示遮罩
            if (isMaskVisible) {
                Log.d(TAG, "Mask already visible");
                return;
            }
            
            // 获取延迟时间
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
            int delay = prefs.getInt(KEY_MASK_DELAY, 2000); // 默认2秒延迟
            
            // 延迟启动遮罩
            if (maskRunnable != null) {
                handler.removeCallbacks(maskRunnable);
            }
            
            maskRunnable = new Runnable() {
                @Override
                public void run() {
                    showMask();
                }
            };
            
            handler.postDelayed(maskRunnable, delay);
            
            Log.d(TAG, "✅ MASK_SCHEDULED_TO_START_IN_" + delay + "_MS");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_STARTING_MASK_IMMEDIATELY", e);
        }
    }
    
    /**
     * 显示黑屏遮罩
     */
    private void showMask() {
        try {
            Log.d(TAG, "🎭 SHOWING_AUTO_MASK");
            
            // 创建纯黑色遮罩视图
            maskView = new android.view.View(this);
            maskView.setBackgroundColor(0xFF000000); // 纯黑色
            maskView.setClickable(true);
            maskView.setFocusable(true);
            
            // 设置触摸事件拦截
            maskView.setOnTouchListener((v, event) -> {
                Log.d(TAG, "🎭 AUTO_MASK_TOUCH_INTERCEPTED - Blocking all touch events");
                return true; // 消费所有触摸事件
            });
            
            // 设置窗口参数
            WindowManager.LayoutParams params = new WindowManager.LayoutParams();
            
            // 设置窗口类型
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                params.type = WindowManager.LayoutParams.TYPE_PHONE;
            }
            
            // 设置窗口标志 - 增强遮罩效果
            params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                         WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                         WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH |
                         WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS |
                         WindowManager.LayoutParams.FLAG_FULLSCREEN |
                         WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
                         WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR |
                         WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS |
                         WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
            
            // 设置窗口格式
            params.format = PixelFormat.TRANSLUCENT;
            
            // 设置窗口大小和位置 - 覆盖整个屏幕包括状态栏
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.height = WindowManager.LayoutParams.MATCH_PARENT;
            params.gravity = Gravity.TOP | Gravity.LEFT;
            
            // 设置状态栏遮罩
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                params.x = 0;
                params.y = 0;
            }
            
            // 添加到窗口管理器
            windowManager.addView(maskView, params);
            isMaskVisible = true;
            
            Log.d(TAG, "✅ AUTO_MASK_DISPLAYED_SUCCESSFULLY");
            Toast.makeText(this, "自动黑屏遮罩已激活", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_SHOWING_AUTO_MASK", e);
            Toast.makeText(this, "显示自动黑屏遮罩失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 隐藏黑屏遮罩
     */
    private void hideMask() {
        try {
            Log.d(TAG, "🎭 HIDING_AUTO_MASK");
            
            if (maskView != null && windowManager != null) {
                windowManager.removeView(maskView);
                maskView = null;
            }
            
            isMaskVisible = false;
            
            Log.d(TAG, "✅ AUTO_MASK_HIDDEN_SUCCESSFULLY");
            Toast.makeText(this, "自动黑屏遮罩已关闭", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_HIDING_AUTO_MASK", e);
            Toast.makeText(this, "隐藏自动黑屏遮罩失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 检查自动黑屏遮罩是否已启用
     */
    public boolean isAutoMaskEnabled() {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        return prefs.getBoolean(KEY_AUTO_MASK_ENABLED, false);
    }
    
    /**
     * 检查遮罩是否可见
     */
    public boolean isMaskVisible() {
        return isMaskVisible;
    }
    
    /**
     * 设置遮罩延迟时间
     */
    public void setMaskDelay(int delayMs) {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        prefs.edit().putInt(KEY_MASK_DELAY, delayMs).apply();
        Log.d(TAG, "✅ MASK_DELAY_SET_TO_" + delayMs + "_MS");
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "AutoMaskService destroyed");
        
        // 清理遮罩
        if (isMaskVisible) {
            hideMask();
        }
        
        // 清理Handler
        if (handler != null && maskRunnable != null) {
            handler.removeCallbacks(maskRunnable);
        }
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
